package com.sky.controller.user;

import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.UserDishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish/")
@Slf4j
@Api(tags = "c端菜品相关接口")
public class DishController {


    @Autowired
    private UserDishService dishService;

    //redis注入对象
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户端查询所有的菜品
     * @return
     */
    @ApiOperation("用户端根据分类id查询菜品")
    @GetMapping("/list")
    public Result<List<DishVO>> DishList(String categoryId){
        //构造redis中的key。dish_分类id
        String key = "dish_"+categoryId;

        //查询redis中是否存在缓存
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);

        //如果存在就访问直接返回redis数据
        if(list != null&& !list.isEmpty()){
            log.info("查询的是redis中的数据");
            return Result.success(list);
        }
        //如果不存在就查询数据库，并且将数据库信息
        log.info("用户端根据分类id查询菜品：{}",categoryId);
        List<DishVO> dishVOList =  dishService.getDishByCategoryId(categoryId);
        log.info(dishVOList.toString());
        //存储到redis中
        redisTemplate.opsForValue().set(key,dishVOList);

        return Result.success(dishVOList);
    }
}

